package com.tuyrt.`as`.proj.main.http

import com.alibaba.android.arouter.launcher.ARouter
import com.tuyrt.`as`.proj.main.route.HiRoute
import com.tuyrt.`as`.proj.main.route.HiRoute.Destination.ACCOUNT_LOGIN
import com.tuyrt.hi.library.restful.HiInterceptor
import com.tuyrt.hi.library.restful.HiResponse

/**
 * 根据response 的 code 自动路由到相关页面
 */
class HttpCodeInterceptor : HiInterceptor {

    override fun intercept(chain: HiInterceptor.Chain): Boolean {
        val response = chain.response()
        // 响应阶段
        if (!chain.isRequestPeriod && response != null) {
            val code = response.code
            when (code) {
                HiResponse.RC_NEED_LOGIN -> {
                    HiRoute.startActivity(null, destination = ACCOUNT_LOGIN)
                }
                // token 过期
                HiResponse.RC_AUTH_TOKEN_EXPIRED, HiResponse.RC_AUTH_TOKEN_INVALID, HiResponse.RC_USER_FORBID -> {
                    var helperUrl: String? = null
                    if (response.errorData != null) {
                        helperUrl = response.errorData!!["helpUrl"]
                    }
                    ARouter.getInstance().build("/degrade/global/activity")
                        .withString("degrade_title", "非法访问")
                        .withString("degrade_desc", response.msg)
                        .withString("degrade_action", helperUrl)
                        .navigation()
                }
            }
        }
        return false
    }
}